package cn.edu.szu;

import java.io.*;

public class Reader extends myThread implements Runnable{

    // 指示当前的id
    private final int id;

    // 当前读者数量
    private static int read_count = 0;

    // 构造方法
    public Reader(int id) {
        this.id = id;
    }

    @Override
    public void run() {
            P(mutex);
            ++ read_count;
            if (read_count == 1) {
                P(rw_mutex);
            }
            V(mutex);

            // It starts reading
            read();

            P(mutex);
            -- read_count;
            if (read_count == 0) {
                V(rw_mutex);
            }
            V(mutex);
        }

    // 读取文件内容的函数
    private void read() {
        String output = "No." + id + " is reading...";
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            printLog(output + "\n" + reader.readLine() + "\n");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
